package com.lsh.oms.core.utils;

/**
 * IP工具类
 * Created by huangdong on 16/8/4.
 */
public class IpUtils {

    private static final long MAX_LONG_IP = 0xffffffffL;

    /**
     * IP字符串转整数
     *
     * @param ip
     * @return
     */
    public static long ip2long(String ip) {
        if (ip == null) {
            throw new NullPointerException("ip is null!");
        }
        String[] array = ip.split("\\.");
        if (array.length != 4) {
            throw new IllegalArgumentException("[" + ip + "] is not a ip!");
        }
        long l0 = Long.parseLong(array[0]);
        long l1 = Long.parseLong(array[1]);
        long l2 = Long.parseLong(array[2]);
        long l3 = Long.parseLong(array[3]);
        if (l0 < 0 || l0 > 255 || l1 < 0 || l1 > 255 || l2 < 0 || l2 > 255 || l3 < 0 || l3 > 255) {
            throw new IllegalArgumentException("ip[" + ip + "] is error!");
        }
        return (l0 << 24) | (l1 << 16) | (l2 << 8) | l3;
    }

    /**
     * IP整数转字符串
     *
     * @param l
     * @return
     */
    public static String long2ip(long l) {
        if (l < 0 || l > MAX_LONG_IP) {
            throw new IllegalArgumentException("long ip[" + l + "] is error!");
        }
        return new StringBuilder().append((l >> 24) & 0xff).append(".").append((l >> 16) & 0xff).append(".").append((l >> 8) & 0xff).append(".").append(l & 0xff).toString();
    }
}
